// Two function need to be implemented , market_handler & market_handler_configMode
// used GM Variables
// ds_marketRuleStep : 进行到哪一步  fir、buy sec、sale sec、buy th、sale th.
// ds_marketRuleCurrent : 当前买卖规则
// ds_marketRuleTryCount : 买卖失败后的

function market_handler(){
    /*
    var buyurl = "/market?by=price&asc=1&type=1&goodstype=0";   //asc 0降序排列 1升序排列  type 1买 2卖  goodstype 0木头 1石头 2水晶 3粮食
    */
    var ps = $("p.msg:contains('您還未建造市場！')");
    if    (ps.length != 0) {
    log("您的城市居然沒有市場,被雷到了!");
    }
    //如果不是由程序自动跳转过来的直接忽略
    if (GM_safeVariables["ds_marketRuleStep"] == null || GM_safeVariables["ds_marketRuleStep"] == "" ) {
        return
    }
    //挂单完成后会跳转到市场页面,这个判断是为了能够区分是否是完成挂单。
    if (GM_safeVariables["ds_marketRuleStep"] == 'sale th') {
            delete GM_safeVariables["ds_marketRuleStep"];
            delete GM_safeVariables["ds_marketRuleCurrent"];
            GM_safeVariables["ds_marketRuleTryCount"] = "0";
            log("掛單成功,跳轉到城市頁面!");
            clickLink("/mindex");
            return;
    }
    
    var isautobuy = CONFIG.market_rules.isautobuy;
    var woodbuyprice = CONFIG.market_rules.woodbuyprice;
    var stonebuyprice = CONFIG.market_rules.stonebuyprice;
    var irishbuyprice = CONFIG.market_rules.irishbuyprice;
    var foodbuyprice = CONFIG.market_rules.foodbuyprice;
    var isautosale = CONFIG.market_rules.isautosale;
    var woodsaleprice = CONFIG.market_rules.woodsaleprice;
    var stonesaleprice = CONFIG.market_rules.stonesaleprice;
    var irishsaleprice = CONFIG.market_rules.irishsaleprice;
    var foodsaleprice = CONFIG.market_rules.foodsaleprice;
    //在出售和购买资源的操作中，都会经历两个跳转步骤，这个标记表示进行到了哪一步
    
    var buypriceList = [];
    if (woodbuyprice != "") {
        var price = new Object();
        price.type = 0;
        price.price = woodbuyprice;
        buypriceList.push(price);
    }
    if (stonebuyprice != "") {
        var price = new Object();
        price.type = 1;
        price.price = stonebuyprice;
        buypriceList.push(price);
    }
    if (irishbuyprice != "") {
        var price = new Object();
        price.type = 2;
        price.price = irishbuyprice;
        buypriceList.push(price);
    }
    if (foodbuyprice != "") {
        var price = new Object();
        price.type = 3;
        price.price = foodbuyprice;
        buypriceList.push(price);
    }
    var salepriceList = [];
    if (woodsaleprice != "") {
        var price = new Object();
        price.type = 0;
        price.price = woodsaleprice;
        salepriceList.push(price);
    }
    if (stonesaleprice != "") {
        var price = new Object();
        price.type = 1;
        price.price = stonesaleprice;
        salepriceList.push(price);
    }
    if (irishsaleprice != "") {
        var price = new Object();
        price.type = 2;
        price.price = irishsaleprice;
        salepriceList.push(price);
    }
    if (foodsaleprice != "") {
        var price = new Object();
        price.type = 3;
        price.price = foodsaleprice;
        salepriceList.push(price);
    }
    //alert("here");
    if (GM_safeVariables["ds_marketRuleStep"] == "fir") {
        //alert("hhh "+ isautobuy+ "  "+isautosale + " "+buypriceList.length + " "+salepriceList.length);
        if (isautobuy && isautosale && buypriceList.length > 0 && salepriceList.length > 0) {
            var dice = rnd(2);
            if (dice == 0) {
                //buy
                //alert("dice buy");
                GM_safeVariables["ds_marketRuleStep"] = "buy sec";
                var dicegoods = rnd(buypriceList.length);
                var price = buypriceList[dicegoods];
                var buyurl = "/market?by=price&asc=1&type=1&goodstype="+price.type;   //asc 0降序排列 1升序排列  type 1买 2卖  goodstype 0木頭 1石头 2水晶 3粮食
                var marketRuleCurrent = new Object();
                var goodstype = "";
                if (price.type == 0) {
                    marketRuleCurrent.goodstype = "木頭";
                } else if (price.type == 1) {
                    marketRuleCurrent.goodstype = "石頭";
                } else if (price.type == 2) {
                    marketRuleCurrent.goodstype = "水晶";
                } else {
                    marketRuleCurrent.goodstype = "糧食";
                } 
                //marketRuleCurrent.type = "buy";
                marketRuleCurrent.goodsprice = price.price;
                GM_safeVariables["ds_marketRuleCurrent"] = uneval(marketRuleCurrent);
                log("進入購買"+marketRuleCurrent.goodstype+"流程！");
                clickLink(buyurl);
                
            } else {
                //sale
                //alert("dice sale");
                GM_safeVariables["ds_marketRuleStep"] = "sale sec";
                var dicegoods = rnd(salepriceList.length);
                var price = salepriceList[dicegoods];
                var saleurl = "/market?type=2";
                var marketRuleCurrent = new Object();
                var goodstype = "";
                if (price.type == 0) {
                    marketRuleCurrent.goodstype = "木頭";
                } else if (price.type == 1) {
                    marketRuleCurrent.goodstype = "石頭";
                } else if (price.type == 2) {
                    marketRuleCurrent.goodstype = "水晶";
                } else {
                    marketRuleCurrent.goodstype = "糧食";
                } 
                //marketRuleCurrent.type = "sale";
                marketRuleCurrent.goodsprice = price.price;
                GM_safeVariables["ds_marketRuleCurrent"] = uneval(marketRuleCurrent);
                log("進入出售"+marketRuleCurrent.goodstype+"流程！");
                clickLink(saleurl);
            }
        } else if (isautobuy && buypriceList.length > 0) {
            //buy
            //alert("buy");
            GM_safeVariables["ds_marketRuleStep"] = "buy sec";
            var dicegoods = rnd(buypriceList.length);
            var price = buypriceList[dicegoods];
            var buyurl = "/market?by=price&asc=1&type=1&goodstype="+price.type;   //asc 0降序排列 1升序排列  type 1买 2卖  goodstype 0木頭 1石頭 2水晶 3糧食
            var marketRuleCurrent = new Object();
            var goodstype = "";
            if (price.type == 0) {
                marketRuleCurrent.goodstype = "木頭";
            } else if (price.type == 1) {
                marketRuleCurrent.goodstype = "石頭";
            } else if (price.type == 2) {
                marketRuleCurrent.goodstype = "水晶";
            } else {
                marketRuleCurrent.goodstype = "糧食";
            } 
            //marketRuleCurrent.type = "buy";
            marketRuleCurrent.goodsprice = price.price;
            GM_safeVariables["ds_marketRuleCurrent"] = uneval(marketRuleCurrent);
            log("進入購買"+marketRuleCurrent.goodstype+"流程！");
            clickLink(buyurl);
        } else if (isautosale && salepriceList.length > 0) {
            //sale
            //alert("sale");
            GM_safeVariables["ds_marketRuleStep"] = "sale sec";
            var dicegoods = rnd(salepriceList.length);
            var price = salepriceList[dicegoods];
            var saleurl = "/market?type=2";
            var marketRuleCurrent = new Object();
            var goodstype = "";
            if (price.type == 0) {
                marketRuleCurrent.goodstype = "木頭";
            } else if (price.type == 1) {
                marketRuleCurrent.goodstype = "石頭";
            } else if (price.type == 2) {
                marketRuleCurrent.goodstype = "水晶";
            } else {
                marketRuleCurrent.goodstype = "糧食";
            } 
            //marketRuleCurrent.type = "sale";
            marketRuleCurrent.goodsprice = price.price;
            GM_safeVariables["ds_marketRuleCurrent"] = uneval(marketRuleCurrent);
            log("進入出售"+marketRuleCurrent.goodstype+"流程！");
            clickLink(saleurl);
        }
    } else {
        var marketRuleCurrent = eval("(" + GM_safeVariables['ds_marketRuleCurrent'] + ")");
        var marketRuleTryCount = parseInt(GM_safeVariables['ds_marketRuleTryCount']);
        if (GM_safeVariables["ds_marketRuleStep"] == "buy sec") {
            //alert("sure buy page");
            var trs = $("html>body>div.container>div.col1>div.market_main>div.m_area>table#ct1.t1>tbody>tr:has(td)").filter(function(index) {
                return index == 0 ;
            });
            var tds = $("td",trs);
            /*
            for (var i = 0 ; i < trs.length ; i++ ) {
                //alert(trs[i].innerHTML);
            }
            for (var i = 0 ; i < tds.length ; i++ ) {
                //alert(tds[i].innerHTML);
            }
            */
            //alert(tds[3].innerHTML);
            //alert(tds[1].innerHTML);
            var i = tds[3].innerHTML.indexOf("0金");
            var j = tds[3].innerHTML.indexOf("銀",i);
            var price = tds[3].innerHTML.substring(i+"0金".length,j);
            if (tds[1].innerHTML == marketRuleCurrent.goodstype && parseInt(price) <= parseInt(marketRuleCurrent.goodsprice)) {
                //alert("here   eeee");
                var nomoney = $(":contains('金幣不足)'",tds);
                //alert(nomoney.length);
                if (nomoney.length == 0) {
                    var urls = $("a",tds).attr("href");
                    log("找到符合價格規則的貨物,自動購買!");
                    GM_safeVariables["ds_marketRuleStep"] = "buy th";
                    clickLink(urls);
                } else {
                    log("金幣不足,跳轉到城市頁面!");
                    delete GM_safeVariables["ds_marketRuleStep"];
                    delete GM_safeVariables["ds_marketRuleCurrent"];
                    GM_safeVariables["ds_marketRuleTryCount"] = "0";
                    clickLink("/mindex");
                }
            } else {
                if (++marketRuleTryCount < 3) {
                    log("未找到符合價格規則的貨物,已經嘗試第"+marketRuleTryCount+"次！");
                    GM_safeVariables["ds_marketRuleStep"] = "fir";
                    GM_safeVariables["ds_marketRuleTryCount"] = ""+marketRuleTryCount;
                    clickLink("/market");
                } else {
                    log("未找到符合價格規則的貨物，嘗試次數超過3次，跳轉到城市頁面！");
                    delete GM_safeVariables["ds_marketRuleStep"];
                    delete GM_safeVariables["ds_marketRuleCurrent"];
                    GM_safeVariables["ds_marketRuleTryCount"] = "0";
                    clickLink("/mindex");
                }
            }
        } else {
            //alert("sure sale page");
            var trs = $("html>body>div.container>div.col1>div.market_main>div.m_area>table#ct3.t1>tbody>tr:contains('"+marketRuleCurrent.goodstype+"')");
            if (trs.length != 0) {
                $("input[name*='amount']",trs).val(2500);
                $("input[name*='goldcoin']",trs).val(0);
                $("input[name*='gradecoin']",trs).val(marketRuleCurrent.goodsprice);
                $("input.btn",trs).click();
                GM_safeVariables["ds_marketRuleStep"] = "sale th";
            } else {
                if (++marketRuleTryCount < 3) {
                    log("可掛單數已滿,推出售賣資源,已經嘗試第"+marketRuleTryCount+"次！");
                    GM_safeVariables["ds_marketRuleStep"] = "fir";
                    GM_safeVariables["ds_marketRuleTryCount"] = ""+marketRuleTryCount;
                    clickLink("/market");
                } else {
                    log("可掛單數已滿,推出售賣資源,嘗試次數超過3次，跳轉到城市頁面！");
                    delete GM_safeVariables["ds_marketRuleStep"];
                    delete GM_safeVariables["ds_marketRuleCurrent"];
                    GM_safeVariables["ds_marketRuleTryCount"] = "0";
                    clickLink("/mindex");
                }
            }
        }
    }
}

function market_handler_configMode(){
    var form1 = $("html>body>div.container>div.col3>form[name*=addlinkform]");
    form1.after([
        '<div class="elink">',
            '<table class="t3">',
                '<tbody>',
                    '<tr>',
                        '<td>'+getDSIconPath()+'配置買賣資源',                       
                    '</tr>',
                    '<tr>',
                        '<td>',
                            '是否自動收購<input type="checkbox"  id="ds_chkAutoBuy"/>',
                        '</td>', 
                    '</tr>',
                    '<tr>',
                        '<td>',
                            '購買單價<input id="ds_cfg_iptwoodbuyprice" type="text" style="width:20px;" value=""/>銀以下的木頭',
                        '</td>', 
                    '</tr>',
                    '<tr>',
                        '<td>',
                            '購買單價<input id="ds_cfg_iptstonebuyprice" type="text" style="width:20px;" value=""/>銀以下的石頭',
                        '</td>', 
                    '</tr>',
                    '<tr>',
                        '<td>',
                            '購買單價<input id="ds_cfg_iptirishbuyprice" type="text" style="width:20px;" value=""/>銀以下的水晶',
                        '</td>', 
                    '</tr>',
                    '<tr>',
                        '<td>',
                            '購買單價<input id="ds_cfg_iptfoodbuyprice" type="text" style="width:20px;" value=""/>銀以下的糧食',
                        '</td>', 
                    '</tr>',
                    '<tr>',
                        '<td>',
                            '資源收購為隨機收購,如果<br/>不輸入價格就是忽略該種資<br>源。',
                        '</td>', 
                    '</tr>',
                    '<tr>',
                        '<td>',
                            '是否自動掛單<input type="checkbox"  id="ds_chkAutoSale"/>',
                        '</td>', 
                    '</tr>',
                    '<tr>',
                        '<td>',
                            '以單價<input id="ds_cfg_iptwoodsaleprice" type="text" style="width:20px;" value=""/>銀出售木頭',
                        '</td>', 
                    '</tr>',
                    '<tr>',
                        '<td>',
                            '以單價<input id="ds_cfg_iptstonesaleprice" type="text" style="width:20px;" value=""/>銀出售石頭',
                        '</td>', 
                    '</tr>',
                    '<tr>',
                        '<td>',
                            '以單價<input id="ds_cfg_iptirishsaleprice" type="text" style="width:20px;" value=""/>銀出售水晶',
                        '</td>', 
                    '</tr>',
                    '<tr>',
                        '<td>',
                            '以單價<input id="ds_cfg_iptfoodsaleprice" type="text" style="width:20px;" value=""/>銀出售糧食',
                        '</td>', 
                    '</tr>',
                    '<tr>',
                        '<td>',
                            '資源收購為隨機收購,如果<br/>不輸入價格就是忽略該種資<br>源。',
                        '</td>', 
                    '</tr>',
                    '<tr>',
                        '<td>',
                            '進入市場的幾率為<input id="ds_cfg_iptdecisionpercent" type="text" style="width:20px;" value=""/>%',
                        '</td>', 
                    '</tr>',
                    '<tr>',
                        '<td>',
                            '較大幾率適合想購買資源<br/>的玩家,小幾率適合防封。',
                        '</td>', 
                    '</tr>',
                    '<tr>',
                        '<td>',
                            '<div><a href="javascript:void(0);" style="margin-left:100px;" class="ds_savecfg">儲存</a></div>',
                        '</td>', 
                    '</tr>',
                '</tbody>',
            '</table>',
        '</div>'
    ].join(''));
    $("a.ds_savecfg").click(function(){
        var rulesisautobuy = $("#ds_chkAutoBuy")[0].checked;
        var ruleswoodbuyprice = $("#ds_cfg_iptwoodbuyprice").val();
        var rulesstonebuyprice = $("#ds_cfg_iptstonebuyprice").val();
        var rulesirishbuyprice = $("#ds_cfg_iptirishbuyprice").val();
        var rulesfoodbuyprice = $("#ds_cfg_iptfoodbuyprice").val();
        var rulesisautosale = $("#ds_chkAutoSale")[0].checked;
        var ruleswoodsaleprice = $("#ds_cfg_iptwoodsaleprice").val();
        var rulesstonesaleprice = $("#ds_cfg_iptstonesaleprice").val();
        var rulesirishsaleprice = $("#ds_cfg_iptirishsaleprice").val();
        var rulesfoodsaleprice = $("#ds_cfg_iptfoodsaleprice").val();
        var rulesdecisionpercent = $("#ds_cfg_iptdecisionpercent").val();
        if (rulesisautobuy) {
            if (ruleswoodbuyprice == "" 
                && rulesstonebuyprice == "" 
                && rulesirishbuyprice == "" 
                && rulesfoodbuyprice == "") {
                alert("如果選擇了自動購買,請至少設置一種資源的購買價格。");
                return;
            }
        }
        if (rulesisautosale) {
            if (ruleswoodsaleprice == "" 
                && rulesstonesaleprice == "" 
                && rulesirishsaleprice == "" 
                && rulesfoodsaleprice == "") {
                alert("如果選擇了自動掛單,請至少設置一種資源的出售價格。");
                return;
            }
        }
        CONFIG.market_rules.decisionpercent = parseInt(rulesdecisionpercent) / 100;
        CONFIG.market_rules.isautobuy = $("#ds_chkAutoBuy")[0].checked;
        CONFIG.market_rules.woodbuyprice = $("#ds_cfg_iptwoodbuyprice").val();
        CONFIG.market_rules.stonebuyprice = $("#ds_cfg_iptstonebuyprice").val();
        CONFIG.market_rules.irishbuyprice = $("#ds_cfg_iptirishbuyprice").val();
        CONFIG.market_rules.foodbuyprice = $("#ds_cfg_iptfoodbuyprice").val();
        CONFIG.market_rules.isautosale = $("#ds_chkAutoSale")[0].checked;
        CONFIG.market_rules.woodsaleprice = $("#ds_cfg_iptwoodsaleprice").val();
        CONFIG.market_rules.stonesaleprice = $("#ds_cfg_iptstonesaleprice").val();
        CONFIG.market_rules.irishsaleprice = $("#ds_cfg_iptirishsaleprice").val();
        CONFIG.market_rules.foodsaleprice = $("#ds_cfg_iptfoodsaleprice").val();
        alert("儲存成功！");
    });
    $("#ds_chkAutoBuy")[0].checked = CONFIG.market_rules.isautobuy;
    $("#ds_cfg_iptwoodbuyprice").val(CONFIG.market_rules.woodbuyprice);
    $("#ds_cfg_iptstonebuyprice").val(CONFIG.market_rules.stonebuyprice);
    $("#ds_cfg_iptirishbuyprice").val(CONFIG.market_rules.irishbuyprice);
    $("#ds_cfg_iptfoodbuyprice").val(CONFIG.market_rules.foodbuyprice);
    $("#ds_chkAutoSale")[0].checked = CONFIG.market_rules.isautosale;
    $("#ds_cfg_iptwoodsaleprice").val(CONFIG.market_rules.woodsaleprice);
    $("#ds_cfg_iptstonesaleprice").val(CONFIG.market_rules.stonesaleprice);
    $("#ds_cfg_iptirishsaleprice").val(CONFIG.market_rules.irishsaleprice);
    $("#ds_cfg_iptfoodsaleprice").val(CONFIG.market_rules.foodsaleprice);
    $("#ds_cfg_iptdecisionpercent").val(CONFIG.market_rules.decisionpercent * 100);
}

function rnd (number) {
    return Math.floor(Math.random() * number);
}

